﻿using Prism.DryIoc;
using Prism.Ioc;
using Prism.Mvvm;
using StarryEdge.Core.Parameter;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace StarryEdge.WPF.Mvvm
{
    public static class RoleLocator
    {
        public static DependencyProperty WriteRoleProperty = DependencyProperty.RegisterAttached("WriteRole", typeof(string), 
            typeof(RoleLocator), new PropertyMetadata(defaultValue: null, propertyChangedCallback: RoleControlChanged));

        public static string GetWriteRole(DependencyObject obj)
        {
            return (string)obj.GetValue(WriteRoleProperty);
        }

        public static void SetWriteRole(DependencyObject obj, string value)
        {
            obj.SetValue(WriteRoleProperty, value);
        }

        private static void RoleControlChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            Prism.Ioc.IContainerExtension container = (Application.Current as PrismApplication).Container as IContainerExtension;
#if !HAS_WINUI
            if (!DesignerProperties.GetIsInDesignMode(d))
#endif
            {
                IUIRoleManage uIRole = container.Resolve<IUIRoleManage>();
                var value = (string)e.NewValue;
                if (!string.IsNullOrEmpty(value))
                {
                    string[] strings = value.Split('_');
                    if (strings.Length != 2)
                    {
                        throw new NotImplementedException("String format error");
                    }
                    uIRole.AddUIRole(new Core.Models.UIRoleModel() { Level = 2, Title = strings[0], Name = strings[1], });
                    UIElement element = d as UIElement;
                    var model = uIRole.GetUIRoleModel(x => x.Name == strings[1] && x.Title == strings[0] && x.Level == 2);
                    if (model != null && model.GuidRoles.Count > 0)
                    {
                        var user = container.Resolve<IUserEntity>().GetLoginUser();
                        if (user != null && user.Role != null)
                        {
                            element.IsEnabled = model.GuidRoles.Any(x => x.Id == user.Role.Id);
                        }
                        else
                        {
                            element.IsEnabled = false;
                        }
                        if (user.Role.Name == "超级管理员" || user.Role.Name == "管理员")
                        {
                            element.IsEnabled = true;
                        }
                        return;
                    }
                    element.IsEnabled = false;
                }
            }
        }
    }
}
